﻿using Devbridge.IPolice.Repositories.Mappings;
using FluentNHibernate.Cfg;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;

namespace Devbridge.IPolice.Repositories.DataContext
{
    public class SessionFactoryProvider
    {
        private readonly static object lockObject = new object();
        private volatile static ISessionFactory sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    lock (lockObject)
                    {
                        if (sessionFactory == null)
                        {
                            sessionFactory = CreateSessionFactory();
                        }
                    }
                }

                return sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        private static ISessionFactory CreateSessionFactory()
        {            
            return Fluently.Configure()
                 .Mappings(m => m.FluentMappings.AddFromAssemblyOf<OffenderMap>())
                 .BuildConfiguration()
                 .BuildSessionFactory();
        }
    }
}
